#!/usr/bin/perl -w
use DBI;
use mydb;
use function;

sub createTask {

        $tid = shift|| 0;
        $total = shift|| 0;

#调度的第一首选是把当前的任务都分散到不同的机器中去，
#如果选出的机器不够并行的数量，则再取出目前空闭的数量，如果目前空闭的数量够的话，则按最大空闲机器倒序，把任务安排下去。


	$sql = "SELECT COUNT(0) FROM c_server WHERE sclass = 'transcode' and status ='normal' and  maxrun > crun";
	print $sql;
	$sth = $dbconn->prepare($sql);

	$sth = $dbconn->prepare($sql) or die $dbconn->errstr;
	$sth->execute() or die "错误: " . $sth->errstr;
	@data0 = $sth->fetchrow();
	$count = $data0[0];

	if(@count >= $total) {

		$sql = "SELECT server FROM c_server WHERE sclass = 'transcode' and status ='normal' and  maxrun > crun limit $totle";
		print $sql;
        	$sth = $dbconn->prepare($sql) or die $dbconn->errstr;
        	$sth->execute() or die "错误: " . $sth->errstr;

        	while(@data0 = $sth->fetchrow()) {

			$row = $sth->rows();
			$server0 = $data0[1];
			setServerTask($server0, $tid, $row);
		}
		return 1;
	}

	$sql = "SELECT SUM(maxrun-crun) FROM c_server WHERE sclass = 'transcode' and status = 'normal' and maxrun > crun";

	print $sql;
	$sth = $dbconn->prepare($sql) or die $dbconn->errstr;
	$sth->execute() or die "错误: " . $sth->errstr;
	@data0 = $sth->fetchrow();
	$sum = $data0[0];

	if($sum < $total) {
		return 0;
	}

	$sql = "SELECT * FROM c_server WHERE sclass = 'transcode' and status = 'normal' and maxrun > crun";
	print $sql;
        $sth = $dbconn->prepare($sql) or die $dbconn->errstr;
        $sth->execute() or die "错误: " . $sth->errstr;

	$i = 1;
        while(@data0 = $sth->fetchrow()) {

                 $server0 = $data0[1];
		 $max = $data0[8];
		 $run = $data0[9];
		 
		 for($m = 0; $m < $max - $run; $m++, $i++) {

                 	if($i > $total) {

				last;
			}

                 	setServerTask($server0, $tid, $i);
		
		}
        }	
	return 1;
}

#设置服务器的任务记录
sub setServerTask {

	$tserver = shift||"";
	$tid = shift||"";
	$row = shift||"";
#设置 servertask中的记录，并修改server中的进行中的线程数量。


        $sql = "SELECT * FROM t_prepare WHERE tid = $tid and cur = $row ";
	print $sql;

        $sth00 = $dbconn->prepare($sql) or die $dbconn->errstr;
        $sth00->execute() or die "错误: " . $sth00->errstr;

        @data00 = $sth00->fetchrow();		

	$pid = $data00[0];
	$level = $data00[3];

	$sql = "insert into c_servertask(server, tid, pid, level, ctime, btime) values(\'$tserver\', $tid, $pid, $level, now(), now())";
        $sth00 = $dbconn->prepare($sql) or die $dbconn->errstr;
        $sth00->execute() or die "错误: " . $sth00->errstr;

	$sql = "update c_server set crun = crun+1 where server = \'$tserver\'";
        $sth00 = $dbconn->prepare($sql) or die $dbconn->errstr;
        $sth00->execute() or die "错误: " . $sth00->errstr;

#更新t_task中的任务状态。

	$sql = "update t_task set status = 'transcode'  where tid = $tid";
        $sth00 = $dbconn->prepare($sql) or die $dbconn->errstr;
        $sth00->execute() or die "错误: " . $sth00->errstr;
}
1;
